package com.zhuiYun.project.api.appletshoppingcart.service.impl;

import com.zhuiYun.project.api.appletshoppingcart.entity.AppletShoppingCartEntity;
import com.zhuiYun.project.api.appletshoppingcart.mapper.AppletShoppingCartMapper;
import com.zhuiYun.project.api.appletshoppingcart.model.AppletShoppingCartModel;
import com.zhuiYun.project.api.appletshoppingcart.service.AppletShoppingCartService;
import com.zhuiYun.project.api.commoditycollection.entity.CommodityCollection;
import com.zhuiYun.project.api.commoditycollection.mapper.CommodityCollectionMapper;
import com.zhuiYun.project.api.handworkdiycollection.entity.HandworkDiyCollection;
import com.zhuiYun.project.api.handworkdiycollection.mapper.HandworkDiyCollectionMapper;
import com.zhuiYun.project.api.userAddress.entiy.UserAddress;
import com.zhuiYun.project.api.userAddress.mapper.UserAddressMapper;
import com.zhuiYun.project.common.errorCode.CommonException;
import com.zhuiYun.project.common.errorCode.EmErrorCode;
import com.zhuiYun.project.common.response.CommonResult;
import com.zhuiYun.project.util.BeanUtils;
import com.zhuiYun.project.util.ObjectUtils;
import com.zhuiYun.project.util.validator.ValidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author lyp
 * @className AppletShoppingCartServiceImpl
 * @description TODO
 * @date 2023/4/5 9:39
 */
@Service
public class AppletShoppingCartServiceImpl implements AppletShoppingCartService {

    @Autowired
    AppletShoppingCartMapper appletShoppingCartMapper;

    @Autowired
    CommodityCollectionMapper commodityCollectionMapper;

    @Autowired
    HandworkDiyCollectionMapper handworkDiyCollectionMapper;

    @Autowired
    UserAddressMapper userAddressMapper;

    /**
     * @return CommonResult
     * @author lyp
     * @description 根据时间类型查询购物车商品
     * @date 2023/4/5 10:19
     * @param: typeId 查询类型id
     * @param: type 查询类型具体说明
     * @param: userId 用户id
     */
    @Override
    public CommonResult selectShoppingCart(Integer typeId, String type, Integer userId) {
        // 验证参数是否为空（自己封装的验证方法）
        if (ObjectUtils.isNotEmpty(typeId) && ObjectUtils.isNotEmpty(type) && ObjectUtils.isNotEmpty(userId)) {
            // 如果要查询所有的购物车记录 前台就传0
            if (typeId == 0 && type.equals("查询全部")) {
                List<AppletShoppingCartEntity> allInfo = appletShoppingCartMapper.getAllInfo(userId);
                return CommonResult.ok(allInfo);
                // 如果要查询1天内或者10天内的记录，就走这个方法
            } else if ((typeId == 1 || typeId == 10) && type.equals("查询一天或者十天内的记录")) {
                List<AppletShoppingCartEntity> inOneOrTenDayInfo = appletShoppingCartMapper.getInOneOrTenDayInfo(typeId, userId);
                return CommonResult.ok(inOneOrTenDayInfo);
                // 如果要查询一个月内的记录就走这个方e法
            } else if (typeId == 1 && type.equals("查询一月内的记录")) {
                List<AppletShoppingCartEntity> inOneMonthInfo = appletShoppingCartMapper.getInOneMonthInfo(typeId, userId);
                return CommonResult.ok(inOneMonthInfo);
            } else if (typeId == 2 && type.equals("查询Diy记录")){
                List<AppletShoppingCartEntity> diyInfo = appletShoppingCartMapper.getDiyInfo(userId);
                return CommonResult.ok(diyInfo);
            } else if (typeId == 1 || typeId == 10 && type.equals("查询一天或十天内的Diy记录")){
                List<AppletShoppingCartEntity> inOneOrTenDayDiyInfo = appletShoppingCartMapper.getInOneOrTenDayDiyInfo(typeId, userId);
                return CommonResult.ok(inOneOrTenDayDiyInfo);
            } else if (typeId == 1 && type.equals("查询一月内Diy的记录")){
                List<AppletShoppingCartEntity> inOneMonthDiyInfo = appletShoppingCartMapper.getInOneMonthDiyInfo(typeId, userId);
                return CommonResult.ok(inOneMonthDiyInfo);
            } else {
                return CommonResult.error(EmErrorCode.PARAMETER_VALIDATION_ERROR);
            }
        } else {
            return CommonResult.error(EmErrorCode.PARAMETER_VALIDATION_ERROR);
        }
    }

    /**
     * @return CommonResult
     * @author lyp
     * @description TODO
     * @date 2023/4/6 20:08
     * @param: id 物品id
     * @param: userId 用户id
     */
    @Override
    public CommonResult delItemsInShoppingCart(AppletShoppingCartModel appletShoppingCartModel) {
        // 物品主键id
        Integer id = appletShoppingCartModel.getId();
        // 用户id
        Integer userId = appletShoppingCartModel.getUserId();
        // 验证参数是否为空（自己封装的验证方法）
        if (ObjectUtils.isNotEmpty(id) && ObjectUtils.isNotEmpty(userId)) {
            int i = appletShoppingCartMapper.delItemsInShoppingCart(id, userId);
            if (i > 0) {
                return CommonResult.ok(EmErrorCode.DELETE_OK);
            } else {
                return CommonResult.error(EmErrorCode.DELETE_ERROR);
            }
        } else {
            return CommonResult.error(EmErrorCode.ID_NULL);
        }
    }

    /**
     * @param appletShoppingCartModel
     * @return CommonResult
     * @author lyp
     * @description 将购物车内的商品移入到我的个人收藏
     * @date 2023/4/7 9:38
     */
    @Transactional
    @Override
    public CommonResult cartMoveIntoCollection(AppletShoppingCartModel appletShoppingCartModel) {
        // 主键id
        Integer id = appletShoppingCartModel.getId();
        // 商品id
        Integer commodityId = appletShoppingCartModel.getCommodityId();
        // 用户id
        Integer userId = appletShoppingCartModel.getUserId();
        // 是否是diy
        Integer isNoDiy = appletShoppingCartModel.getIsNoDiy();
        // diy id
        Integer diyId = appletShoppingCartModel.getDiyId();
        // 验证参数是否为空（自己封装的验证方法）
        if (ObjectUtils.isNotEmpty(commodityId) && ObjectUtils.isNotEmpty(userId) && ObjectUtils.isNotEmpty(id) && isNoDiy==0) {
            int i = appletShoppingCartMapper.delItemsInShoppingCart(id, userId);
            CommodityCollection commodityCollection = new CommodityCollection();
            commodityCollection.setCommodityId(commodityId);
            commodityCollection.setUserId(userId);
            commodityCollection.setCreateTime(new Date());
            commodityCollection.setUpdateTime(new Date());
            commodityCollection.setDelFlag(0);
            int i1 = commodityCollectionMapper.insertSelective(commodityCollection);
            if (i > 0 && i1 > 0) {
                return CommonResult.ok(EmErrorCode.UPDATE_OK);
            } else {
                return CommonResult.error(EmErrorCode.UPDATE_ERROR);
            }
            // diy移入收藏
        } else if(ObjectUtils.isNotEmpty(userId) && ObjectUtils.isNotEmpty(id) && isNoDiy==1 && ObjectUtils.isNotEmpty(diyId)){
            int i = appletShoppingCartMapper.delItemsInShoppingCart(id, userId);
            HandworkDiyCollection handworkDiyCollection = new HandworkDiyCollection();
            handworkDiyCollection.setHandworkDiyId(diyId);
            handworkDiyCollection.setUserId(userId);
            handworkDiyCollection.setCreateTime(new Date());
            handworkDiyCollection.setUpdateTime(new Date());
            handworkDiyCollection.setDelFlag(0);
            int i1 = handworkDiyCollectionMapper.insertSelective(handworkDiyCollection);
            if (i > 0 && i1 > 0) {
                return CommonResult.ok(EmErrorCode.UPDATE_OK);
            } else {
                return CommonResult.error(EmErrorCode.UPDATE_ERROR);
            }
        }else{
            return CommonResult.error(EmErrorCode.PARAMETER_VALIDATION_ERROR);
        }
    }

    /**
     * @param appletShoppingCartModel
     * @return CommonResult
     * @author lyp
     * @description 持久化用户购物车信息 例如 ：加了一个商品数量等
     * @date 2023/4/7 11:46
     */
    @Override
    public CommonResult persistingUserShoppingCartInfo(AppletShoppingCartModel appletShoppingCartModel) {
        // 用户id
        Integer userId = appletShoppingCartModel.getUserId();
        // 变更商品的主键id
        Integer id = appletShoppingCartModel.getId();
        // 商品要变更的数量
        Integer number = appletShoppingCartModel.getNumber();
        // 判断他们是否为空
        if (ObjectUtils.isNotEmpty(userId) && ObjectUtils.isNotEmpty(id) && ObjectUtils.isNotEmpty(number)) {
            int i = appletShoppingCartMapper.persistingUserShoppingCartInfo(userId, id, number);
            if (i > 0) {
                return CommonResult.ok(EmErrorCode.UPDATE_OK);
            } else {
                return CommonResult.error(EmErrorCode.UPDATE_ERROR);
            }
        } else {
            return CommonResult.error(EmErrorCode.PARAMETER_VALIDATION_ERROR);
        }
    }

    /**
     * @return CommonResult
     * @author lyp
     * @description 持久化用户选中商品
     * @date 2023/4/8 9:22
     * @param: appletShoppingCartModel
     */
    @Override
    public CommonResult persistingFlag(AppletShoppingCartModel appletShoppingCartModel) throws CommonException {
        // 判断用户id 类选id不能为空
        if (ObjectUtils.isNotEmpty(appletShoppingCartModel.getUserId()) && ObjectUtils.isNotEmpty(appletShoppingCartModel.getTypeId())) {
            // 用户id
            Integer userId = appletShoppingCartModel.getUserId();
            // 操作类型id
            Integer typeId = appletShoppingCartModel.getTypeId();
            // 主键id 可以商品的唯一标识id
            Integer id = appletShoppingCartModel.getId();
            // 全选
            if (typeId == 1) {
                String flag = "true";
                int i = appletShoppingCartMapper.persistingFlag(flag, userId);
                if (i > 0) {
                    return CommonResult.ok(EmErrorCode.UPDATE_OK);
                } else {
                    return CommonResult.error(EmErrorCode.UPDATE_ERROR);
                }
                // 取消全选
            } else if (typeId == 2) {
                String flag = "false";
                int i = appletShoppingCartMapper.persistingFlag(flag, userId);
                if (i > 0) {
                    return CommonResult.ok(EmErrorCode.UPDATE_OK);
                } else {
                    return CommonResult.error(EmErrorCode.UPDATE_ERROR);
                }
                // 单选选中商品 主键 id和typeId
            } else if(typeId == 3 && ObjectUtils.isNotEmpty(appletShoppingCartModel.getId())){
                String flag = "true";
                int i = appletShoppingCartMapper.persistingOneFlag(flag, userId, id);
                if (i > 0) {
                    return CommonResult.ok(EmErrorCode.UPDATE_OK);
                } else {
                    return CommonResult.error(EmErrorCode.UPDATE_ERROR);
                }
                // 单选取消勾选商品
            } else if(typeId == 4 && ObjectUtils.isNotEmpty(appletShoppingCartModel.getId())){
                String flag = "false";
                int i = appletShoppingCartMapper.persistingOneFlag(flag, userId, id);
                if (i > 0) {
                    return CommonResult.ok(EmErrorCode.UPDATE_OK);
                } else {
                    return CommonResult.error(EmErrorCode.UPDATE_ERROR);
                }
            } else {
                return CommonResult.error(EmErrorCode.PARAMETER_VALIDATION_ERROR);
            }
        } else {
            return CommonResult.error(EmErrorCode.PARAMETER_VALIDATION_ERROR);
        }
    }

    /**
     * @author lyp
     * @description 用户结算购物车内的商品
     * @date 2023/4/10 11:36
     * @param
     * @return CommonResult
     */
    @Override
    public CommonResult closeAnAccount() throws CommonException {
        return null;
    }

    /**
     * @author lyp
     * @description 用户结算购物车内的商品，进行商品查询
     * @date 2023/4/11 13:28
     * @param: userId 用户id
     * @return CommonResult
     */
    @Override
    public CommonResult getShoppingCartInfo(Integer userId) {
        if(ObjectUtils.isNotEmpty(userId)){
            List<AppletShoppingCartEntity> shoppingCartInfo = appletShoppingCartMapper.getShoppingCartInfo(userId);
            BigDecimal bigDecimal = new BigDecimal(0);
            for(AppletShoppingCartEntity appletShoppingCartEntity : shoppingCartInfo){
                // 商品最终单价
                BigDecimal diyFavorablePrice = appletShoppingCartEntity.getFavPrice();
                // 商品数量
                Integer number = appletShoppingCartEntity.getNumber();
                BigDecimal multiply = diyFavorablePrice.multiply(BigDecimal.valueOf(number));
                bigDecimal = bigDecimal.add(multiply);
                appletShoppingCartEntity.setShoppingPriceSum(bigDecimal);
            }
            return CommonResult.ok(shoppingCartInfo);
        }else{
            return CommonResult.error(EmErrorCode.PARAMETER_VALIDATION_ERROR);
        }
    }

    /**
     * @author lyp
     * @description 用户结算购物车内的diy，进行diy查询
     * @date 2023/4/11 14:53
     * @param: userId 用户id
     * @return CommonResult
     */
    @Override
    public CommonResult getShoppingCartInfoDiy(Integer userId){
        if(ObjectUtils.isNotEmpty(userId)){
            List<AppletShoppingCartEntity> shoppingCartInfo = appletShoppingCartMapper.getShoppingCartInfoDiy(userId);
            BigDecimal bigDecimal = new BigDecimal(0);
            for(AppletShoppingCartEntity appletShoppingCartEntity : shoppingCartInfo){
                // 商品最终单价
                BigDecimal diyFavorablePrice = appletShoppingCartEntity.getDiyFavorablePrice();
                // 商品数量
                Integer number = appletShoppingCartEntity.getNumber();
                BigDecimal multiply = diyFavorablePrice.multiply(BigDecimal.valueOf(number));
                bigDecimal = bigDecimal.add(multiply);
                appletShoppingCartEntity.setShoppingDiyPriceSum(bigDecimal);
            }
            return CommonResult.ok(shoppingCartInfo);
        }else{
            return CommonResult.error(EmErrorCode.PARAMETER_VALIDATION_ERROR);
        }
    }

    /**
     * @author lyp
     * @description 查询用户默认地址
     * @date 2023/4/14 9:02
     * @param userId
     * @return CommonResult
     */
    @Override
    public CommonResult getUserAddress(Integer userId) {
        if(ObjectUtils.isNotEmpty(userId)){
            UserAddress userDefaultAddress = userAddressMapper.getUserDefaultAddress(userId);
            return CommonResult.ok(userDefaultAddress);
        }else{
            return CommonResult.error(EmErrorCode.OBJECT_NOT_NULL);
        }
    }
}
